var express = require('express');
var { User, UserInfo } = require('../../sql/user_mysql');
const router = express.Router();
// var decrypt = require('../../utils/decrypt');
var generatorToken = require('../../utils/generatorToken');
var randomStr = require('../../utils/randomStr');
router.post('/login', async (req, res) => {
	let { username, password } = req.body;

	// let username = decrypt(unUser);
	// let password = decrypt(unPass);

	let user = await User.findOne({
		where: {
			username,
		},
	});
	let token = generatorToken(username);
	if (!user) {
		await User.create({
			username,
			password,
			token,
		});
		// res.cookie('mobile_token', token, {
		// 	maxAge: 604800000,
		// 	httpOnly: false,
		// });
		let user = await User.findOne({ where: { username } });
		await UserInfo.create({
			nickname: `新用户` + randomStr(10),
			userId: user.id,
		});
		res.send({
			status: true,
			data: {
				token,
				id: user.id,
			},
			message: '登录成功！',
		});
		return;
	}

	if (password != user.password) {
		res.send({
			status: false,
			message: '密码错误！',
		});
		return;
	}
	User.update(
		{ token },
		{
			where: {
				username: username,
			},
		}
	);
	// res.cookie('mobile_token', token, {
	// 	maxAge: 604800000,
	// 	httpOnly: true,
	// });

	res.send({
		status: true,
		token,
		message: '登录成功！',
	});
});

router.get('/userInfo', async (req, res) => {});

module.exports = router;
